import { Col, Icon, Row, Spin } from "antd";
import { Card, ListView, SearchBar, Tabs, WhiteSpace } from "antd-mobile";
import { addon } from "pao-aop";
import { reactControl, ReactView, ReactViewControl, ReactViewState } from "pao-aop-client";
import React from "react";
import { getWebViewRetObjectType, request, setMainFormTitle, subscribeWebViewNotify, setMainFormBack } from "src/business/util_tool";
import { AppServiceUtility } from "src/projects/app/appService";
import { ROUTE_PATH } from "src/projects/app/util-tool";
import './index.less';
const tabs = [
    { title: '距离' },
    { title: '时间' },
    { title: '报名数' },
    { title: '收藏数' },
];
function MyBody(props: any) {
    return (
        <Row className="am-list-body my-body" style={{ height: '100%' }}>
            {props.children}
        </Row>
    );
}
/**
 * 组件：活动列表视图控件状态
 */
export interface ActivityListViewState extends ReactViewState {

    /** 长列表数据 */
    dataSource?: any;
    /** 请求的数据 */
    list: any[];
    /** 上拉加载 */
    upLoading?: boolean;
    /** 下拉刷新 */
    pullLoading?: boolean;
    /** 长列表容器高度 */
    height?: any;
    /** 当前第几页 */
    page: any;
    /** 记录tab状态 */
    tab_status?: string;
    // 搜索关键词
    keyword?: string;
    location?: any;

    empty: any;
    animating: any;
    pageCount: number;
}

const cfg: any = {
    // 报名中
    'enroll': 0,
    // 已满员
    'fully': 1,
    // 进行中
    'progress': 2,
    // 已结束
    'finish': 3,
};

export function getGoodLookTimeShow(begin_date: string, end_date: string) {
    if (!begin_date && !end_date) {
        // 否则就显示年月日
        return null;
    }
    if (!begin_date || !end_date) {
        // 否则就显示年月日
        return `${begin_date} - ${end_date}`;
    }
    let by = begin_date.slice(0, 4);
    let bm = begin_date.slice(5, 7);
    let bd = begin_date.slice(8, 10);
    let ey = end_date.slice(0, 4);
    let em = end_date.slice(5, 7);
    let ed = end_date.slice(8, 10);
    // 如果都是一天内，就只显示一个
    let nyear = new Date().getFullYear();
    // 2020-01-02 09:30:00 2020-01-02 10:30:00
    let string: string = '';

    // 开始时间的年份为基准
    if (Number(by) !== nyear) {
        // 非今年的都要加
        string += `${by}`;
    }
    // 月份直接加
    if (Number(by) !== nyear) {
        string += string === '' ? `${bm}` : `.${bm}`;
    } else {
        // string += string === '' ? `${Number(bm) + ''}月` : `${Number(bm) + ''}月`;
        string += `${Number(bm) + ''}月`;
    }
    // 日期直接加
    if (Number(by) !== nyear) {
        string += string === '' ? `${bd}` : `.${bd}`;
    } else {
        // string += string === '' ? `${bd}` : `${Number(bd) + ''}日`;
        string += `${Number(bd) + ''}日`;
    }
    // 时间直接加
    string += ` ${begin_date.slice(11, -3)} - `;

    let eflag = false;
    if (ey !== by && Number(ey) !== nyear) {
        // 结束时间非今年的并且跟开始年份不一样的都要加
        string += `${ey}.`;
        eflag = true;
    }
    if (eflag || em !== bm || ed !== bd) {
        // 加了年份日期不一样就要加
        if (Number(ey) !== nyear) {
            string += `${Number(bm) + ''}.${Number(ed) + ''}`;
        } else {
            string += `${Number(em) + ''}月${Number(ed) + ''}日`;
        }
    }
    // 时间直接加
    string += ` ${end_date.slice(11, -3)}`;
    return string;
}
export function getTag(type: any) {
    const spanWidth = 7;
    const style = {
        borderRadius: '5px',
        color: '#fff',
        padding: '2px',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
    };
    if (type === '已满员') {
        return (
            <Col span={spanWidth} style={{ background: "#ffc000", ...style }}>已满员</Col>
        );
    } else if (type === '已结束') {
        return (
            <Col span={spanWidth} style={{ background: "#595959", ...style }}>已结束</Col>
        );
    } else if (type === '进行中') {
        return (
            <Col span={spanWidth} style={{ background: "#5b9bd5", ...style }}>进行中</Col>
        );
    } else if (type === '报名中') {
        return (
            <Col span={spanWidth} style={{ background: "#ed7d31", ...style }}>报名中</Col>
        );
    }
    return (
        <Col span={spanWidth} />
    );
}
/**
 * 组件：活动列表视图控件
 */
export class ActivityListView extends ReactView<ActivityListViewControl, ActivityListViewState> {
    constructor(props: any) {
        super(props);
        const ds = new ListView.DataSource({
            rowHasChanged: (r1: any, r2: any) => r1 !== r2
        });
        this.state = {
            dataSource: ds,
            list: [
                [],
                [],
                [],
                [],
            ],
            upLoading: false,
            pullLoading: false,
            // height: document.documentElement!.clientHeight * 0.75,
            // height: 400,
            page: [
                1, 1, 1, 1
            ],
            tab_status: tabs[0]['title'],
            keyword: '',
            location: undefined,
            empty: [
                false,
                false,
                false,
                false,
            ],
            animating: [
                true,
                true,
                true,
                true,
            ],
            pageCount: 10,
        };
    }
    componentDidMount() {
        const { tab_status } = this.state;
        if ((window as any).ReactNativeWebView) {
            const messageCb = (e: any) => {
                const retObject = JSON.parse(e.data);
                if (getWebViewRetObjectType(retObject) === 'getPhonePosition') {
                    const location = retObject.data;
                    if (location === undefined) {
                        // Toast.fail('获取位置信息失败');
                    }
                    this.setState(
                        {
                            location: retObject.data
                        },
                        () => {
                            this.refreshAllActivity(tab_status);
                        }
                    );
                }
            };
            subscribeWebViewNotify(messageCb);
        } else {
            this.refreshAllActivity(tab_status);
        }
        this.getPhonePosition();
    }
    getPhonePosition() {
        // Toast.info('认证成功：' + e.data);
        if ((window as any).ReactNativeWebView) {
            (window as any).ReactNativeWebView.postMessage(
                JSON.stringify({
                    function: 'getPhonePosition',
                    params: undefined
                })
            );
        }
    }
    /** 明细点击事件 */
    on_click_detail = (id: string) => {
        this.props.history!.push(ROUTE_PATH.activityDetail + '/' + id + '/' + this.state.tab_status);
    }
    /** tab切换触发事件 */
    tab_click = (tab: any, index: number) => {
        let tab_status = tabs[index] ? tabs[index].title : tabs[0].title;
        this.refreshAllActivity(tab_status);
    }
    refreshAllActivity(tab_status: any, page: number = 1) {
        for (let i in cfg) {
            if (cfg.hasOwnProperty(i)) {
                console.log('refreshAllActivity', page + 1);
                this.getActivityList(tab_status, i, page, false);
            }
        }
    }
    getActivityList(tab_status: any, type: any, newPage: number, isConcact: boolean) {
        let { list, keyword, location, animating, empty, page, pageCount } = this.state;
        let param: any = { 'sort': tab_status };
        if (this.props.match!.params.key) {
            param['organization_id'] = this.props.match!.params.key;
        }
        if (keyword !== '') {
            param['activity_name'] = keyword;
        }
        if (tab_status === '距离') {
            param = { ...param, ...location };
        }
        param['status'] = type;
        let idx = cfg[type];
        // 新页数
        page[idx] = newPage;
        // 加载动画
        animating[idx] = true;
        // 赋值参数
        let extra: any = {
            animating
        };
        // 不是要组合数据
        if (isConcact === false) {
            // 数据清空
            list[idx] = [];
            // 取消空状态
            empty[idx] = false;
            // 赋值
            extra['list'] = list;
        }
        this.setState(
            {
                ...extra,
            },
            () => {
                request(this, AppServiceUtility.activity_service.get_activity_list!(param, newPage, pageCount))
                    .then((data: any) => {
                        console.log(data);
                        if (data && data.result.length > 0) {
                            list[idx] = isConcact ? list![idx].concat(data.result) : data.result;
                            animating[idx] = false;
                            this.setState({
                                list,
                                page,
                                tab_status,
                                animating,
                            });
                        } else {
                            animating[idx] = false;
                            empty[idx] = true;
                            this.setState({
                                animating,
                                empty,
                                page,
                            });
                        }
                    });
            }
        );
    }
    searchKey(e: any) {
        this.setState(
            {
                keyword: e,
                empty: [
                    false,
                    false,
                    false,
                    false,
                ],
                list: [
                    [],
                    [],
                    [],
                    [],
                ],
            },
            () => {
                this.refreshAllActivity(this.state.tab_status);
            }
        );
    }
    // 判断是否进行状态
    endOrIng(begin_date: any, end_date: any) {
        const begin_date_time = new Date(begin_date).getTime();
        const end_date_time = new Date(end_date).getTime();
        const now_date_time = new Date().getTime();
        if (now_date_time > end_date_time) {
            return 0;
            // return (
            //     <Row className="tag end">已结束</Row>
            // );
        } else if (now_date_time <= end_date_time && now_date_time >= begin_date_time) {
            return 1;
            // return (
            //     <Row className="tag ing">进行中</Row>
            // );
        } else if (now_date_time < begin_date_time) {
            return 2;
            // return (
            //     <Row className="tag end">未开始</Row>
            // );
        } else {
            return null;
        }
    }
    /** 下拉事件 */
    onEndReached(type: any) {
        const { animating, page, tab_status } = this.state;
        const idx = cfg[type];
        if (animating[idx] === true) {
            return;
        }
        this.getActivityList(tab_status, type, page[idx] + 1, true);
    }
    render() {
        const { list, dataSource, animating, empty } = this.state;
        // 获取item进行展示
        setMainFormTitle('活动列表');
        setMainFormBack('', () => {
            this.props.history!.push(ROUTE_PATH.communityList);
        });
        const renderRow = (owData: any, sectionID: any, rowID: any, type: any = false) => {
            return (
                <Card className='list-conten' onClick={() => this.on_click_detail(owData.id)}>
                    <Row type='flex' justify='center'>
                        <Col className='list-col' span={10}><img className="activity-img" src={owData.photo && owData.photo[0] ? owData.photo[0] : 'https://www.e-health100.com/api/attachment/activityphoto/8336'} /></Col>
                        <Col span={14} className='list-col'>
                            <Row>
                                <Col span={17} className="happiness-info-row-title" style={{ WebkitBoxOrient: 'vertical' }}>{owData.activity_name}</Col>
                                {getTag(type)}
                            </Row>
                            <Row className='list-row'>{owData.organization_name}</Row>
                            <Row>{getGoodLookTimeShow(owData.begin_date, owData.end_date)}</Row>
                            <Row>
                                <Col span={4} className="font-orange">{!owData.hasOwnProperty('amount') || owData.amount === 0 || owData.amount === '0' || owData === '' || owData.amount === undefined ? '免费' : `￥${owData['amount'] || 0}`}</Col>
                                <Col span={14}>已报名：{owData.participate_count || 0}/{owData.max_quantity}</Col>
                                <Col span={6}><Icon className='item-icon-size' type="star" />{owData.collection_count || 0}</Col>
                            </Row>
                        </Col>
                    </Row>
                </Card>
            );
        };
        return (
            <Row>
                <SearchBar placeholder="搜索" maxLength={8} onSubmit={(e: any) => this.searchKey(e)} />
                <Tabs
                    tabs={tabs}
                    initialPage={0}
                    onTabClick={(tab, index) => this.tab_click(tab, index)}
                />
                <Card className='list-conten'>
                    <Card.Header
                        title="报名中"
                    />
                    {list && list[0] && list[0].length ? <Row className='tabs-content'>
                        <ListView
                            ref={el => this['lv'] = el}
                            dataSource={dataSource.cloneWithRows(list[0])}
                            renderRow={(owData: any, sectionID: any, rowID: any) => renderRow(owData, sectionID, rowID, '报名中')}
                            initialListSize={10}
                            pageSize={10}
                            renderBodyComponent={() => <MyBody />}
                            style={list[0].length > 4 ? { height: 640 } : { height: list[0].length * 160 }}
                            onEndReached={() => this.onEndReached('enroll')}
                        />
                    </Row> : null}
                    {
                        animating[0] ? <Row>
                            <WhiteSpace size="lg" />
                            <Row style={{ textAlign: 'center' }}>
                                <Spin size="large" />
                            </Row>
                        </Row> : null
                    }
                    {
                        empty[0] ? <Row>
                            <WhiteSpace size="lg" />
                            <Row className='tabs-content' type='flex' justify='center'>{list && list[0] && list[0].length ? '已经是最后一条了' : '无数据'}</Row>
                        </Row> : null
                    }
                    <WhiteSpace size="lg" />
                </Card>
                <Card className='list-conten'>
                    <Card.Header
                        title="已满员"
                    />
                    {list && list[1] && list[1].length ? <Row className='tabs-content'>
                        <ListView
                            ref={el => this['lv'] = el}
                            dataSource={dataSource.cloneWithRows(list[1])}
                            renderRow={(owData: any, sectionID: any, rowID: any) => renderRow(owData, sectionID, rowID, '已满员')}
                            initialListSize={10}
                            pageSize={10}
                            renderBodyComponent={() => <MyBody />}
                            style={list[1].length > 4 ? { height: 640 } : { height: list[1].length * 160 }}
                            onEndReached={() => this.onEndReached('fully')}
                        />
                    </Row> : null}
                    {
                        animating[1] ? <Row>
                            <WhiteSpace size="lg" />
                            <Row style={{ textAlign: 'center' }}>
                                <Spin size="large" />
                            </Row>
                        </Row> : null
                    }
                    {
                        empty[1] ? <Row>
                            <WhiteSpace size="lg" />
                            <Row className='tabs-content' type='flex' justify='center'>{list && list[1] && list[1].length ? '已经是最后一条了' : '无数据'}</Row>
                        </Row> : null
                    }
                    <WhiteSpace size="lg" />
                </Card>
                <Card className='list-conten'>
                    <Card.Header
                        title="进行中"
                    />
                    {list && list[2] && list[2].length ? <Row className='tabs-content'>
                        <ListView
                            ref={el => this['lv'] = el}
                            dataSource={dataSource.cloneWithRows(list[2])}
                            renderRow={(owData: any, sectionID: any, rowID: any) => renderRow(owData, sectionID, rowID, '进行中')}
                            initialListSize={10}
                            pageSize={10}
                            renderBodyComponent={() => <MyBody />}
                            style={list[2].length > 4 ? { height: 640 } : { height: list[2].length * 160 }}
                            onEndReached={() => this.onEndReached('progress')}
                        />
                    </Row> : null}
                    {
                        animating[2] ? <Row>
                            <WhiteSpace size="lg" />
                            <Row style={{ textAlign: 'center' }}>
                                <Spin size="large" />
                            </Row>
                        </Row> : null
                    }
                    {
                        empty[2] ? <Row>
                            <WhiteSpace size="lg" />
                            <Row className='tabs-content' type='flex' justify='center'>{list && list[2] && list[2].length ? '已经是最后一条了' : '无数据'}</Row>
                        </Row> : null
                    }
                    <WhiteSpace size="lg" />
                </Card>
                <Card className='list-conten'>
                    <Card.Header
                        title="已结束"
                    />
                    {list && list[3] && list[3].length ? <Row className='tabs-content'>
                        <ListView
                            ref={el => this['lv'] = el}
                            dataSource={dataSource.cloneWithRows(list[3])}
                            renderRow={(owData: any, sectionID: any, rowID: any) => renderRow(owData, sectionID, rowID, '已结束')}
                            initialListSize={10}
                            pageSize={10}
                            renderBodyComponent={() => <MyBody />}
                            style={list[3].length > 4 ? { height: 640 } : { height: list[3].length * 160 }}
                            onEndReached={() => this.onEndReached('finish')}
                        />
                    </Row> : null}
                    {
                        animating[3] ? <Row>
                            <WhiteSpace size="lg" />
                            <Row style={{ textAlign: 'center' }}>
                                <Spin size="large" />
                            </Row>
                        </Row> : null
                    }
                    {
                        empty[3] ? <Row>
                            <WhiteSpace size="lg" />
                            <Row className='tabs-content' type='flex' justify='center'>{list && list[3] && list[3].length ? '已经是最后一条了' : '无数据'}</Row>
                        </Row> : null
                    }
                    <WhiteSpace size="lg" />
                </Card>
            </Row>
        );
    }
}

/**
 * 组件：活动列表视图控件
 * 控制活动列表视图控件
 */
@addon('ActivityListView', '活动列表视图控件', '控制活动列表视图控件')
@reactControl(ActivityListView, true)
export class ActivityListViewControl extends ReactViewControl {
    constructor() {
        super();
    }
}